package demo11.gumballstatewinner;
/**
 * 糖果机器
 * 状态模式：允许对象在内部状态改变时改变它的行为，对象看起来好像修改了它的类。
 *      将状态封装成了独立的类，并将动作委托到代表当前状态的对象，行为会随着内部状态而改变。
 * */
public class GumballMachine {
//将每一种状态都分装成类，便于扩展
	
	State soldOutState;//卖完状态
	State noQuarterState;//没有投币
	State hasQuarterState;//投币
	State soldState;//在卖
	State winnerState;//中奖者
 
	State state = soldOutState;//实例变量持有一种状态对象
	int count = 0;//记录糖果数的实例变量
 
	
	public GumballMachine(int numberGumballs) {
		//所有状态对象都在构造其中创建并赋值
		//1每个状态的行为都局部化到它具体的类中2 在他们具体类中删除if语句方便日后维护
		//3让每个状态对修改关闭，而“糖果机器对扩展开放”，这样可以加入新的状态类
		soldOutState = new SoldOutState(this);//this代表本类当前对象
		noQuarterState = new NoQuarterState(this);
		hasQuarterState = new HasQuarterState(this);
		soldState = new SoldState(this);
		winnerState = new WinnerState(this);

		this.count = numberGumballs;
 		if (numberGumballs > 0) {
			state = noQuarterState;
		} 
	}
 //将动作委托到代表当前状态的对象state
	public void insertQuarter() {
		state.insertQuarter();
	}
 
	public void ejectQuarter() {
		state.ejectQuarter();
	}
 
	public void turnCrank() {
		state.turnCrank();
		state.dispense();
	}

	
 
	void releaseBall() {
		System.out.println("一个口香糖来轧出槽...");
		if (count != 0) {
			count = count - 1;
		}
	}
 
	int getCount() {
		return count;
	}
 //重新添加糖果
	void refill(int count) {
		this.count += count;
		System.out.println("口香糖机只是补充；它是新的计数: " + this.count);
		state.refill();
	}

    public State getState() {
        return state;
    }
      void setState(State state) {//修改状态
		this.state = state;
	}
    public State getSoldOutState() {
        return soldOutState;
    }

    public State getNoQuarterState() {
        return noQuarterState;
    }

    public State getHasQuarterState() {
        return hasQuarterState;
    }

    public State getSoldState() {
        return soldState;
    }

    public State getWinnerState() {
        return winnerState;
    }
 
	@Override
	public String toString() {
		StringBuffer result = new StringBuffer();
		result.append("\njava站口香糖模型机器\n");
		result.append("\n库存: " + count + " 糖果");
		if (count != 1) {
			result.append("AAA");
		}
		result.append("\n");
		result.append("机器状态 是 " + state + "\n");
		return result.toString();
	}
}
